package com.jctrip.hotel.management.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jctrip.hotel.domain.dao.HtRouteInfoDao;
import com.jctrip.hotel.domain.dao.MgQunarinCloseLogDao;
import com.jctrip.hotel.domain.entity.HtRouteInfo;
import com.jctrip.hotel.domain.entity.MgOrderLog;
import com.jctrip.hotel.domain.entity.MgQunarinCloseLog;
import com.jctrip.hotel.management.client.QunarinClient;
import com.jctrip.hotel.management.model.param.CloseStoreParam;
import com.jctrip.hotel.management.model.result.BaseResult;
import com.jctrip.hotel.management.model.result.GetCloseLogsResult;
import com.jctrip.hotel.management.model.result.GetRouteCodeResult;
import com.jctrip.hotel.management.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: ch
 * @CreateTime: 2023/12/25 2:59 PM
 * @Description:
 */
@Service
@Slf4j
public class QunarinSystemService {
    @Autowired
    private QunarinClient qunarinClient;
    @Autowired
    private HtRouteInfoDao htRouteInfoDao;
    @Autowired
    private MgQunarinCloseLogDao mgQunarinCloseLogDao;


    public String closeStore(CloseStoreParam param, HttpServletRequest request){
        if (StringUtils.isBlank(param.getRouteId()) || StringUtils.isBlank(param.getHours().toString())){
            throw new RuntimeException("参数不全");
        }
        HtRouteInfo htRouteInfo = htRouteInfoDao.selectOne(new LambdaQueryWrapper<HtRouteInfo>()
                    .eq(HtRouteInfo::getRouteId,param.getRouteId()));
        if (null == htRouteInfo){
            throw new RuntimeException("未找到该店铺");
        }
        if (StringUtils.isBlank(htRouteInfo.getThirdSecret())){
            throw new RuntimeException("未配置第三方密钥");
        }
        BaseResult baseResult = qunarinClient.closeAnyStore(param.getHours(), htRouteInfo.getThirdSecret());
        String message = "";
        switch (baseResult.getErrorCode()){
            case "0000":
                message = "下线成功"+param.getHours()+"小时";
                break;
            case "0018":
                message = "推送小时不符合要求";
                break;
            case "0019":
                message = "hmac失效";
                break;
            case "0020":
                message = "已永久下线,请上线后操作";
                break;

        }
        insertQunarLog(message, htRouteInfo.getRouteId(), htRouteInfo.getRouteName(), request);
        return message;
    }

    public GetRouteCodeResult listRouteCode(){
        List<HtRouteInfo> list = htRouteInfoDao.selectList(new LambdaQueryWrapper<HtRouteInfo>()
                .eq(HtRouteInfo::getRouteCode,"qunarDom"));
        List<GetRouteCodeResult.RouteCodeInfo> records = new ArrayList<>();
        list.forEach(htRouteInfo -> {
            GetRouteCodeResult.RouteCodeInfo routeCodeInfo = GetRouteCodeResult.RouteCodeInfo.builder().build();
            routeCodeInfo.setCode(htRouteInfo.getRouteId());
            routeCodeInfo.setId(htRouteInfo.getId());
            routeCodeInfo.setName(htRouteInfo.getRouteName());
            records.add(routeCodeInfo);
        });
        return GetRouteCodeResult.builder()
                .routeCodeInfoList(records)
                .build();
    }
    public GetCloseLogsResult listCloseLogs(Integer pageNum,
                                            Integer pageSize,
                                            String routeId){
        Page<MgQunarinCloseLog> mgQunarinCloseLogPage = mgQunarinCloseLogDao.selectPage(new Page<>(pageNum,pageSize),new LambdaQueryWrapper<MgQunarinCloseLog>()
                .eq(StringUtils.isNotBlank(routeId),MgQunarinCloseLog::getRouteId,routeId).orderByDesc(MgQunarinCloseLog::getCreateTime));
        List<GetCloseLogsResult.CloseLogInfo> closeLogInfos = Optional.ofNullable(mgQunarinCloseLogPage.getRecords()).orElse(new ArrayList<>())
                .stream().map(e -> GetCloseLogsResult.CloseLogInfo.builder()
                        .info(e.getInfo())
                        .operator(e.getOperator())
                        .createTime(e.getCreateTime())
                        .routeName(e.getRouteName())
                        .build())
                .collect(Collectors.toList());
        return GetCloseLogsResult.builder()
                .records(closeLogInfos)
                .current(mgQunarinCloseLogPage.getCurrent())
                .total(mgQunarinCloseLogPage.getTotal())
                .size(mgQunarinCloseLogPage.getSize())
                .pages(mgQunarinCloseLogPage.getPages())
                .lastTime(mgQunarinCloseLogPage.getTotal()>0? closeLogInfos.get(0).getInfo().startsWith("下线成功")?closeLogInfos.get(0).getCreateTime() : null: null)
                .build();
    }



    private void insertQunarLog(String message,String routeId, String routeName ,HttpServletRequest request){
        MgQunarinCloseLog mgQunarinCloseLog = new MgQunarinCloseLog();
        mgQunarinCloseLog.setInfo(message);
        mgQunarinCloseLog.setRouteId(routeId);
        mgQunarinCloseLog.setRouteName(routeName);
        mgQunarinCloseLog.setOperator(StringUtils.isNotBlank(request.getHeader("token")) ?
                JwtUtil.parseJwt(request.getHeader("token")).getSubject():"system");
        mgQunarinCloseLogDao.insert(mgQunarinCloseLog);
    }

}
